# -- coding: utf-8 --
# @Time : 2024/2/8 10:51
# @Author : rlh
# @File : regist_index.py
# 功能描述:

# 系统第三方库
from flask import Blueprint, render_template, request, redirect,url_for, flash
from .service_regist import ApiConfigHandle_cls
from core.logging_utils_module import logs
# 导入项目模块

index_bp = Blueprint('regist_index', __name__, template_folder="templates", static_folder="static")

# 前端接口 -- 接口注册
@index_bp.route('/regist_api', methods=['GET', 'POST'] )
def regist_api():
    if request.method == 'GET':
        return render_template('Api_Register.html')
    elif request.method == 'POST':
        # 调用后端注册接口
        message = ApiConfigHandle_cls.add_api_data()
        flash(message, 'success')  
        return redirect(url_for('regist_index.show_api_lis'))



# 前端接口 -- 展示接口列表
@index_bp.route('/show_api_lis', methods=['GET', 'POST'] )
def show_api_lis():
    api_data = ApiConfigHandle_cls.read_apidata_all()
    return render_template('show_api_lis.html', api_data=api_data )


# 前端接口 -- 接口编辑与详情
@index_bp.route('/api_detail', methods=['GET', 'POST'] )
@index_bp.route('/show_ApiData', methods=['GET', 'POST'] )
def show_ApiData():
    api_name = request.args.get('api_name')

    host = request.host
    try:
        api_data, data = ApiConfigHandle_cls.dis_api_data(api_name=api_name)
        url_path = api_data[2]
        url = 'http://'+host+url_path
        # 根据不同的路由返回不同的模板
        if request.path == '/api_detail':
            template_file = 'api_detail.html'  # 页面详情模板
        else:
            template_file = 'show_api_data.html'  # 页面编辑模板
        return render_template(template_file, api_name=api_data[1],url_path=url_path,url=url,
                                data=data,description=api_data[4])
    except Exception as e:
        messages1 = '{} 接口查询失败'.format(api_name)
        messages2 = '失败原因:{}'.format(e)
        flash(messages1, 'error')
        logs.log('error', messages1)(messages2)        
        return redirect(url_for('regist_index.show_api_lis'))




#  前端接口 -- 删除API数据
@index_bp.route('/delete_api', methods=['GET','POST'])
def delete_user_route():
    api_name = request.args.get('api_name')
    success = ApiConfigHandle_cls.del_api_data(api_name=api_name)
    if success:
        flash('接口删除成功', 'success')
    else:
        flash('接口删除失败', 'error')
    return redirect(url_for('regist_index.show_api_lis'))



# 前端接口 -- 修改接口
@index_bp.route('/update_api', methods=['GET', 'POST'] )
def update_api():
    success = ApiConfigHandle_cls.update_api_data()
    if success:
        flash('接口更新成功', 'success')
    else:
        flash('接口更新失败', 'error')
    return redirect(url_for('regist_index.show_api_lis'))
    # api_name = request.form.get('api_name')
    # return redirect(url_for('regist_index.show_ApiData', api_name=api_name))

